package com.sciai.Service.impl;

import cn.com.sciai.aix.common.http.SciaiHttpResponseEntity;
import cn.com.sciai.aix.common.http.SciaiHttpResponseEntityBuilder;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sciai.Service.TBusinessService;
import com.sciai.common.CommonConstant;
import com.sciai.entity.FilePath;
import com.sciai.entity.Weather;
import com.sciai.entity.WeatherType;
import com.sciai.entity.req.BusinessGenerateReq;
import com.sciai.entity.vo.ConentVo;
import com.sciai.entity.vo.ConentVoText;
import com.sciai.entity.vo.LoginUserInfo;
import com.sciai.entity.vo.WeatherVo;
import com.sciai.mapper.SysLoginUserDao;
import com.sciai.mapper.WeatherMapper;
import com.sciai.utils.AddressUtil;
import com.sciai.utils.RandomOffsetXY;
import com.sciai.utils.StringManipulation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 天气信息 服务实现类
 * </p>
 *
 * @author tqx
 * @since 2023-09-26
 */
@Service
public class TBusinessServiceImpl extends ServiceImpl<WeatherMapper, Weather> implements TBusinessService {
    @Value("${file.downloadImag}")
    private String downloadImag;
    @Resource
    private WeatherMapper weatherMapper;
    @Value("${file.imagPath}")
    private String imagPath;
    @Resource
    private SysLoginUserDao sysLoginUserDao;
    @Override
    public SciaiHttpResponseEntity generateTask(BusinessGenerateReq req) {
        try {
            List<Weather> weathers =new ArrayList<>();
            List<String> strings = Arrays.asList(req.getWeatherType().split(","));
            for (int y=0;y<strings.size();y++){
                Weather weather = new Weather();

//                LoginUserInfo userInfo  =(LoginUserInfo)  StpUtil.getSession().get(CommonConstant.SESSION_USER_KEY);
                weather.setCreateTime(new Date());
                weather.setCreateUserId(Integer.valueOf(req.getId()));
                weather.setName(req.getName());
                weather.setContactInformation(req.getContactInformation());
                weather.setWeatherType(Integer.valueOf(strings.get(y)));
                Map<String, Object> params2 = new HashMap<>();
                params2.put("id",Integer.valueOf(strings.get(y)));
                List<WeatherType> weatherTypes = weatherMapper.queryWeatherType(params2);
                if (weatherTypes.size()!=1){
                    return SciaiHttpResponseEntityBuilder.builder().error("500", "没有天气类型的基础数据！").build();
                }
                weather.setWeatherTypeName(weatherTypes.get(0).getTypeName());
                weather.setOccurrenceTime(req.getOccurrenceTime());
                weather.setOccurrencePlace1(req.getLongitude());
                weather.setOccurrencePlace2(req.getLatitude());
                weather.setHail(req.getHail());
                weather.setImagUuid(req.getImagUuid());
                weather.setVideoUuid(req.getVideoUuid());
                weather.setDescribeName(req.getDescribeName());
                if (req.getOccurrencePlace().isEmpty()|| req.getOccurrencePlace().equals("") || req.getOccurrencePlace().equals("null")
                || req.getOccurrencePlace()==null){
                    //需要调研高德API去获取
                    double a1 = Double.parseDouble(req.getLongitude());
                    double a2 = Double.parseDouble(req.getLatitude());
                    String addressInfo = AddressUtil.getProvinceCityDistrict(a1, a2);
                    List<String> parts = Arrays.asList(addressInfo.split(",")); // 拆分成 "City:大连市" 和 "District:甘井子区"
                    weather.setOccurrencePlace(parts.get(0)+parts.get(1)+parts.get(2));
                }else {
                    weather.setOccurrencePlace(req.getOccurrencePlace());
                }
                weathers.add(weather);
            }

            if (this.saveBatch(weathers)){
                return SciaiHttpResponseEntityBuilder.builder().ok("提交成功！").build();
            }else {
                return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！").build();
            }
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }

    @Override
    public SciaiHttpResponseEntity queryWeather(Date date1, Date date2,String  type) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("date1",date1);
            params.put("date2",date2);
            List<Weather> list = weatherMapper.queryWeather(params);
            List<WeatherVo> list1 =new ArrayList<>();
            for (int r =0 ; r < list.size();r++){
                    //游客
                    Weather weather =list.get(r);
                    WeatherVo weatherVo =new WeatherVo();
                    ConentVo conentVo =new ConentVo();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                    String time = simpleDateFormat.format(weather.getOccurrenceTime());

                    String weatherTypeName=weather.getWeatherTypeName();
                    String name = "";
                    if (type.equals("0")){
                        name="***";
                    }else if (type.equals("1")){
//                        name=weather.getName().substring(1)+"**";
                        name= StringManipulation.manipulateString(weather.getName());
                    }else {
                        name=weather.getName();
                    }
                    ConentVoText text = new ConentVoText();
                    text.setWeatherTypeName(weatherTypeName);
                    text.setName(name);
                    conentVo.setContent(text);
                    conentVo.setPadding(7);
                    conentVo.setBorderRadius(5);
                    conentVo.setDisplay("BYCLICK");
                    conentVo.setBgColor("#FFFFFF");

                    weatherVo.setCustomCallout(conentVo);
                    weatherVo.setId(weather.getId());
                    weatherVo.setRotate(0);
                    if (weather.getDescribeName().length()>40){
                        String str = weather.getDescribeName();
                        weatherVo.setDescribeName(str.substring(0,40));
                    }else {
                        weatherVo.setDescribeName( weather.getDescribeName());
                    }
                    weatherVo.setWidth(30);
                    weatherVo.setHeight(30);
                    weatherVo.setAlpha(0.5);
                    weatherVo.setCreateTime(weather.getOccurrenceTime());
                    if (weather.getType()==1){
                        weatherVo.setLatitude(weather.getOccurrencePlace2());
                        weatherVo.setLongitude(weather.getOccurrencePlace1());
                        weatherVo.setRemark("感谢您提供!");
                        if (weather.getWeatherType()==1 || weather.getWeatherType()==4){
                            //冰雹或者大冰雹
                            weatherVo.setIconPath("/static/blue.png");
                        }else if(weather.getWeatherType()==2){
                            //龙卷
                            weatherVo.setIconPath("/static/red.png");
                        }else if(weather.getWeatherType()==3){
                            //云图
                            weatherVo.setIconPath("/static/green.png");
                        }else {
                            weatherVo.setIconPath("/static/gray.png");
                        }
                    }else {
                        List<String> list2 = RandomOffsetXY.offsetXY(weather.getOccurrencePlace2(),weather.getOccurrencePlace1());
                        weatherVo.setLatitude(list2.get(0));
                        weatherVo.setLongitude(list2.get(1));
                        weatherVo.setRemark("信息来自网络，仅供参考!");
                        if (weather.getWeatherType()==1 || weather.getWeatherType()==4){
                            //冰雹或者大冰雹
                            weatherVo.setIconPath("/static/lightblue.png");
                        }else if(weather.getWeatherType()==2){
                            //龙卷
                            weatherVo.setIconPath("/static/lightred.png");
                        }else if(weather.getWeatherType()==3){
                            //云图
                            weatherVo.setIconPath("/static/green.png");
                        }else {
                            //其它类型
                            weatherVo.setIconPath("/static/gray.png");
                        }
                    }

                    //查询文件
                    Map<String, Object> params5 = new HashMap<>();
                    params5.put("uuid",weather.getImagUuid());
                    List<FilePath> filePaths = weatherMapper.queryFilePath(params5);
                    List<String>  list2 =new ArrayList<>();

                      for (int h = 0 ;h<filePaths.size();h++){
                          // base64图片 存储的byte数组
                          byte[] baseByte= new byte[0];
                          // 从本地resource目录下获取图片
//                          ClassPathResource classPathResource = new ClassPathResource("/file/imag"+filePaths.get(h).getPath());
                          String filePath2 = imagPath+filePaths.get(h).getPath();
                          File localFlie = new File(filePath2);
                          // base64图片前缀
                          String pre = "data:image/jpg;base64,";
                          // 读取图片
                          FileInputStream fileInputStream = new FileInputStream(localFlie);
                          // 读取字节长度
                          int len = 0;
                          // baseByte数组的容量
                          int capacity = 0;
                          byte [] bytes = new byte[1024];
                          while ((len = fileInputStream.read(bytes)) != -1){
                              // 对原数组进行拷贝扩容
                              baseByte= Arrays.copyOf(baseByte, len + capacity);
                              // 将新数据拷贝到新扩容的数组
                              System.arraycopy(bytes, 0, baseByte, capacity, len);
                              // 数据容量增加
                              capacity += len;
                          }
                          // 获取base64编码器
                          Base64.Encoder encoder = Base64.getEncoder();
                          // 将字节数组转换base64
                          String encodeToString = encoder.encodeToString(baseByte);
                          String strImage = pre+encodeToString;
                          String paths="";
                          //http://124.70.45.54:8101/static/export/2023-10-16/nephogram_search.csv //例子
                          paths=paths+downloadImag+filePaths.get(h).getPath();
                          list2.add(paths);
                      }
                      weatherVo.setImg(list2);

                list1.add(weatherVo);
            }
            List<List<WeatherVo>> lists = splitList(list1, 200);
            return SciaiHttpResponseEntityBuilder.builder().ok(lists).build();
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }

    /**
     * 将list分成多份list
     *
     * @param list list对象
     * @param num  每份的数量
     * @return List<List < T>>
     */
    public static <T> List<List<T>> splitList(List<T> list, Integer num) {
        int listSize = list.size();
        ArrayList<List<T>> objects1 = new ArrayList<>();
        int n = 0;
        for (int i = 0; i < listSize / num; i++) {
            ArrayList<T> objects = new ArrayList<>();
            for (; n < num * (i + 1); n++) {
                objects.add(list.get(n));
            }
            objects1.add(objects);
        }
        //处理余数问题
        int a = listSize % num != 0 ? listSize % num : 0;
        for (int i = 0; i < a; i++) {
            ArrayList<T> objects = new ArrayList<>();
            for (; n < num * (listSize / num) + a; n++) {
                objects.add(list.get(n));
            }
            if (!CollectionUtils.isEmpty(objects)) {
                objects1.add(objects);
            }
        }
        return objects1;
    }
}
